// 奖品名称数组
let prizesArr = ["谢谢", "奶茶", "汉堡", "咖啡", "西瓜", "鸡腿", "柠檬", "蛋糕"];
// 图片数组
let arrBigImg = ["./img/1-beer.png", "./img/2-milk.png", "./img/3-hamburg.png",
  "./img/4-coffee.png", "./img/5-watermelon.png", "./img/6-drumstick.png",
  "./img/7-lemon.png", "./img/8-cake.png", "./img/9-prizes.png"];

//获取所有奖品单元格
let allPrizesLi = document.querySelectorAll('.prizes-li');
// 获取图片
let prizesImg = document.querySelectorAll('.pic');

// 旋转初始值
let count = 0;
let isClick = true;
let index = 3;
// 转到哪个位置
let prizesPosition = 0;

// 绑定图片
for (let j = 0;j < prizesImg.length; j++) {
  prizesImg[j].src = arrBigImg[j];
}
// 旋转速度。值越大，速度越慢
let speed = 500;

// 旋转功能
function roll() {
  // 速度衰减
  speed -= 50;
  if (speed <= 10) {
    speed = 10;
  }

  // 删除每个调用的所有活动类名
  for (let j = 0; j < allPrizesLi.length; j++) {
    allPrizesLi[j].classList.remove('active-li');
  }
  prizesPosition++;

  // 计算转次数
  if (prizesPosition >= allPrizesLi.length - 1) {
    prizesPosition = 0;
    count++;
  }

  allPrizesLi[prizesPosition].classList.add('active-li');
  let initSpeed = 500;
  let timer;
  // 总转数
  let totalCount = 5;

  // 当达到转弯次数和指定位置时停止
  if (count >= totalCount && (prizesPosition + 1) === index) {
    clearTimeout(timer);
    isClick = true;
    speed = initSpeed;
    //等待1秒打开弹出窗口
    timer = setTimeout(openDialog, 1000);
  } else {
    // 等待1秒打开弹出窗口
    timer = setTimeout(roll, speed);
    // Last lap deceleration
    if (count >= totalCount - 1 || speed <= 50) {
      speed += 100;
    }
  }
}

//绘制开始功能
function startDraw() {
  // 防止多次触发
  if (isClick) {
    count = 0;
    // 随机生成中奖位置
    index = Math.floor(Math.random() * prizesArr.length + 1);
    roll();
    isClick = false;
  }
}

function openDialog() {
  linkObj.messageFromHtml(prizesArr[prizesPosition]);
}